package crawler.guanzhi;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zql.entity.AgencyEntity;

import util.HttpConnectionGet;
import util.MybatisTool;
import util.TianYanCha;

public class GuanZhiQiCheCrawler {
	public List<AgencyEntity> getAgency() {
		List<AgencyEntity> list = new ArrayList<AgencyEntity>();
		String getDealer = "http://cjb.qorosauto.com/cjb/dealers";
		String dealerText = HttpConnectionGet.getJson(getDealer);
		JSONArray dealerArray = JSON.parseObject(dealerText).getJSONObject("data").getJSONArray("dealers");
		for(int i=0;i<dealerArray.size();i++) {
			JSONObject dealer = dealerArray.getJSONObject(i);
			String name = dealer.getString("fullName_Cn");
			String sellTell = dealer.getString("telephone");
			String address = dealer.getString("address_Cn");
			String proName = dealer.getJSONArray("region_Cn").getString(1);
			String cityName = dealer.getJSONArray("region_Cn").getString(2);
			String typeCode = dealer.getString("dealerLevel");
			String type = null;
			if("1".equals(typeCode)) {
				type = "授权经销商";
			} else if ("2".equals(typeCode)) {
				type = "快销店";
			}
			String lng = dealer.getJSONArray("coordinate").getString(1);
			String lat = dealer.getJSONArray("coordinate").getString(0);
			List<String> shareholder = TianYanCha.getShareholder(name);
			String sControllingShareholder = shareholder.get(0);
			String sOtherShareholders = shareholder.get(1);
			
			AgencyEntity agency = new AgencyEntity();
			agency.setdCloseDate(null);
			agency.setdOpeningDate(null);
			agency.setdUpdateTime(new Timestamp(System.currentTimeMillis()));
			agency.setnBrandID(-1);
			agency.setsBrand("观致");

			agency.setnDealerIDWeb(-1);
			agency.setnManufacturerID(-1);
			agency.setsManufacturer("观致汽车");

			agency.setnState(1);
			agency.setsAddress(address);
			agency.setsCity(cityName);
			agency.setsCustomerServiceCall(null);
			agency.setsDealerName(name);
			agency.setsDealerType(type);
			agency.setsProvince(proName);
			agency.setsSaleCall(sellTell);
			agency.setsLongitude(lng);
			agency.setsLatitude(lat);
			agency.setsControllingShareholder(sControllingShareholder);
			agency.setsOtherShareholders(sOtherShareholders);
			list.add(agency);

		}
		
		
		return list;
	}
	public static void main(String[] args) {
		GuanZhiQiCheCrawler crawler = new GuanZhiQiCheCrawler();
		System.out.println("爬虫开始...");
		List<AgencyEntity> agencys = crawler.getAgency();
		System.out.println("抓取完毕,正在存库");
		for(AgencyEntity agency : agencys) {
			MybatisTool.save(agency);
		}
		MybatisTool.close();
		System.out.println("请查看数据库");

		
	}

}
